// use ::function_name::named;
// use atty::Stream;
use colored::Colorize;
use std::env;
use std::env::consts;
use std::io::{self, Write};
use std::io::{IsTerminal, stdout};
use sysinfo::System;

//------ 导出常用的类型、trait 或宏; 给用户使用; 将会导出到 crate root, 而不是本模块 root

//=============== 打印当前函数路径
#[macro_export]
macro_rules! function_path {
    () => {
        cyan_println!(
            "-------------------- func: {}",
            concat!(module_path!(), "::", function_name!())
        );
    };
}

//=============== 打印间隔
pub fn my_sep() {
    println!("{}", "===============================".green());
}

pub fn my_sep_sub() {
    println!("{}", "-------------------------------".green());
}

//=============== 暂停
pub fn my_pause() {
    print!("Press Enter to continue...");
    io::stdout().flush().unwrap();
    let mut _input = String::new();
    io::stdin().read_line(&mut _input).unwrap();
}

//============= 打印程序运行的系统信息
// 递归查找并打印父进程信息
fn find_parent_process(
    system: &System,
    parent_pid: Option<sysinfo::Pid>,
    end_level: usize,
    level: usize,
) -> Option<()> {
    if level > end_level || parent_pid.is_none() {
        return Some(());
    }

    let pid = parent_pid.unwrap();
    print!("parent {level} process pid: {pid}, ");

    system.process(pid).and_then(|proc| {
        println!("parent {level} process name: {:?}", proc.name());
        find_parent_process(system, proc.parent(), end_level, level + 1)
    })
    /*
    .or_else(|| {
        println!("parent {level} process doesn't exsit");
        None
    })
    */
}

pub fn my_prt_sys_info() {
    println!("===================================== system info");

    // ---------------------- 打印 os信息
    println!("This OS type  : {}", consts::OS); // 输出如 "linux", "windows", "macos"
    println!("This os family: {}", consts::FAMILY); // 输出 "unix" 或 "windows"

    // -------------------- 是否在 TTY 设备 中运行
    if stdout().is_terminal() {
        println!("I'm a tty");
    } else {
        println!("I'm not a tty");
    }

    // ---------------------- 打印环境变量
    my_sep_sub();
    let env_strs = ["WT_SESSION", "PROMPT", "COMSPEC", "TERM_PROGRAM", "ANSICON", "TERM"];
    for e_str in env_strs {
        env::var(e_str).map_or_else(
            |e| {
                println!(r#"$env.{e_str} => "{e}""#);
            },
            |v| {
                println!("$env.{e_str} => {v}");
            },
        );
    }

    //----------------------- 进程 pid, name
    my_sep_sub();
    let system = System::new_all();
    sysinfo::get_current_pid().map_or_else(
        |e| {
            println!("get_current_pid() error: {e}");
            None
        },
        |this_pid| {
            print!("This process PID: {this_pid}, ");
            let this_proc = system.process(this_pid);
            match this_proc {
                Some(proc) => {
                    println!("This process name: {:?}", proc.name());
                    // 递归查找父进程，最多 end_level 层
                    find_parent_process(&system, proc.parent(), 8, 1)
                }
                None => {
                    println!("This process not found");
                    None
                }
            }
        },
    );
    println!();
}

// ========================== 检测是否在 windows terminal 中运行
pub fn my_is_run_in_windows_terminal() -> bool {
    std::env::var("WT_SESSION").is_ok()
}

pub enum MyOSType {
    Windows,
    Linux,
    MacOS,
    Unknown,
}

pub fn my_is_windows() -> MyOSType {
    #[cfg(target_os = "windows")]
    return MyOSType::Windows;

    #[cfg(target_os = "linux")]
    return MyOSType::Linux;

    #[cfg(target_os = "macos")]
    return MyOSType::MacOS;
}

pub fn my_set_tty_colored() -> bool {
    let ret = match my_is_windows() {
        MyOSType::Windows => {
            // 检查是否在 Windows Terminal 中运行
            if my_is_run_in_windows_terminal() {
                // 在 Windows Terminal 中运行
                println!("Running in Windows Terminal");
                true
            } else {
                // 不在 Windows Terminal 中运行
                println!("Not running in Windows Terminal");
                false
            }
        }
        _ => {
            // 不在 Windows 中运行
            println!("Not running on Windows");
            true
        }
    };
    colored::control::set_override(ret);
    ret
}
